import React, { PureComponent } from 'react';
import { Form, Input, Table, Button, Icon,notification,Modal } from 'antd';
import StructureTreeSelect from "./structureTreeSelect"
import { connect } from 'dva';
class sectionStructures extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            selectActive: true,
            loading: false,
            selectedRowKeys: [],
            data: [],
            extra:{}
        }
        this.addStructures = this.addStructures.bind(this)
        this.onSelect = this.onSelect.bind(this)
        this.getData = this.getData.bind(this)
        this.massEditProp=this.massEditProp.bind(this)
        this.replaceComponent=this.replaceComponent.bind(this)
        this.deleteComponent=this.deleteComponent.bind(this)
        this.massDelete=this.massDelete.bind(this)
        this.refresh=this.refresh.bind(this)
        this.massReplace=this.massReplace.bind(this)
    }

    componentDidMount(){
        if(this.props.onLoaded){
            this.props.onLoaded(this)
        }
    }
     async componentWillMount() {
         let {sectionData}=this.props;
        let typeData=await this.props.getTopDefinitionTreeList({bridgeId: sectionData.bridgeId,sectionId:sectionData.id})
        if(typeData&&typeData.length){
            const len= typeData.length
            for (let i = 0; i <len; i++) {
                let item = typeData[i];
                item.title=item.name;
                item.key=item.id;
                item.value=item.id
                
            }
        }
        this.setState({
            treeData:typeData
        })
        this.getData()
    }
    async onSelect(keys, e) {
        let { extra } = this.state;
        let {id } = e.props;
        extra.definitionTypeParentId=id;
        await this.setState({
            extra
        })
        this.getData()
    }
    massDelete(e) {
        e.preventDefault();
        Modal.confirm({
            title: "提示",
            content: "是否删除选中构件?",
            okText:"确定",
            cancelText:"取消",
            onOk:()=>{
                let {sectionData,treeContext,goInnerPage,deleteDefinitionInstance}=_this.props;
                let { selectedRowKeys,data } = this.state;
                if (selectedRowKeys && selectedRowKeys.length) {
                    let sidArr = []
                    let arr = []
                    const len=selectedRowKeys.length
                    for (let i = 0; i < len; i++) {
                        let item = selectedRowKeys[i];
                        // arr.push("topStructureComponentUnit" + item)
                        const sid = data.find(unit => unit.id == item)
                        sidArr.push(sid)
                    }
                    let sids= sidArr.map(item=>item.sid)
                    deleteDefinitionInstance({ definitionInstanceIds: selectedRowKeys,selectionOrSpanIds:Array.from(new Set(sids)), type: "top",bridgeId:sectionData.bridgeId }, res => {
                        if(res&&res.length){
                            const len=res.length
                            for (let i = 0; i < len; i++) {
                                const item = res[i];
                                arr.push("topStructureComponentUnit"+item)
                            }
                        }
                       treeContext.removeTreeNode(arr)
                        if (goInnerPage) {
                            goInnerPage(null, 'results', '操作成功')
                        }
                    }, err => {

                    })
                } else {
                    notification.warn({ message: "请选择构件" })
                }
            },
            onCancel() { },
        })

    }
    async getData() {
        let {extra}=this.state;
        this.setState({
            loading: true
        })
        let { sectionData } = this.props;
        let res = await this.props.getTopDefinitionInstanceList({ sid: sectionData.id,...extra})
        this.setState({
            data: res,
            loading: false,
        })
    }
    addStructures() {
        let { sectionData,modalContext } = this.props;
        sectionData.selectedRowKeys=[sectionData.id]
        sectionData.sid=sectionData.id
        sectionData.type="top"
        sectionData.operateType="add"
        sectionData.nodeType="3"
        modalContext.updateModal({
            visible: true,
            title: "选择构件",
            event: { code:"structureSelect"},
            extra:sectionData
          });
        }
    massEditProp(e){
        if(e){
            e.preventDefault();
        }
        let arr=[],arr2=[]
        let {selectedRowKeys,data}=this.state;
        if(selectedRowKeys&&selectedRowKeys.length){
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                const item = selectedRowKeys[i];
                const obj = data.find(item2 => item2.id == item)
                arr.push(obj.definitionTreeId)
                arr2.push(obj.sid)
            }
            let same=!arr.some(function (value, index) {
                return value != arr[0];
            });
            if(!same){
                notification.warn({message:"只能选择同类构件!"})
                return;
            }else{
                let obj = data.find(item=>item.id==selectedRowKeys[0]);
                obj.selectedRowKeys=selectedRowKeys
                obj.type="top"
                obj.sids=arr2
                this.props.goInnerPage(null,'componentEdit',obj.definitionType,obj)
            }
        }else{
            notification.warn({message:"请至少选择一个构件!"})
            return;
        }
    }
    async editComponentProp(e, item) {
        let selectedRowKeys=[];
        selectedRowKeys.push(item.id)
        e.preventDefault();
        await this.setState({
            selectedRowKeys
        })
        this.massEditProp()
    }
    deleteComponent(e, item) {
        let selectedRowKeys=[item.id]
        e.preventDefault();
        Modal.confirm({
            title: "提示",
            content: "是否删除选中构件?",
            okText:"确定",
            cancelText:"取消",
            onOk:()=>{
                let {deleteDefinitionInstance,treeContext,goInnerPage}=this.props;
                if (selectedRowKeys && selectedRowKeys.length) {
                   deleteDefinitionInstance({ definitionInstanceIds: selectedRowKeys,selectionOrSpanIds:[item.sid], type: "top",bridgeId:sectionData.bridgeId }, res => {
                        let arr=[]
                        if(res&&res.length){
                            const len=res.length
                            for (let i = 0; i < len; i++) {
                                const item = res[i];
                                arr.push("topStructureComponentUnit"+item)
                            }
                        }
                       treeContext.removeTreeNode(arr)
                        if (goInnerPage) {
                           goInnerPage(null, 'results', '操作成功')
                        }
                    }, err => {

                    })
                } else {
                    notification.warn({ message: "请选择构件" })
                }
            },
            onCancel() { },
        })
    }
    refresh(){
        this.setState({
            selectedRowKeys:[]
        })
        this.getData()
    }
    massReplace(e){
        e.preventDefault()
        let {sectionData,modalContext}=this.props;
        let {selectedRowKeys,data}=this.state;
        let definitionTreeLevel;
        let arr=[],arr2=[],arr3=[],arr4=[],arr5=[],arr6=[]
        if(selectedRowKeys&&selectedRowKeys.length){
            const len=selectedRowKeys.length
            for (let i = 0; i < len; i++) {
                let item = selectedRowKeys[i];
                const len2=data.length
                for (let j = 0; j < len2; j++) {
                    let item2 = data[j];
                    if(item2.id==item){
                        arr.push(item2.definitionTreeId);
                        arr2.push(item2.sid);
                        arr3.push(item2.id)
                        arr4.push(item2.definitionId)
                        arr5.push(item2)
                        arr6.push(item2.spanType)
                        definitionTreeLevel=item2.definitionTreeLevel;
                    }
                }
            }
            let same = !arr.some(function (value, index) {
                return value != arr[0];
            });
            if(!same){
                notification.warn({message:"只能选择同类构件!"})
                return;
            }
            if (modalContext) {
                modalContext.updateModal({
                    visible: true,
                    title: "替换构件",
                    event: { code: "structureSelect" },
                    extra: {
                        sid:arr2,
                        definitionTreeIds: arr,
                        definitionTemps: Array.from(new Set([...arr4])),
                        originalData: arr5,
                        "nodeType": 3,
                        definitionTreeLevel,
                        definitionIds:arr3,
                        tid:arr[0],
                        spanType:arr6[0],
                        type:"top",
                        operateType:"update",
                        bridgeId:sectionData.bridgeId
                    }
                });
            }
        }else{
            notification.warn({message:"请选择构件!"})
        }
    }
    replaceComponent(e,item){
        if (e) {
            e.preventDefault()
        }
        let { sectionData,modalContext } = this.props
        let definitionIds = [item.id]
        if (modalContext) {
           modalContext.updateModal({
                visible: true,
                title: "替换构件",
                event: { code: "structureSelect" },
                extra: {
                    sid: item.sid,
                    definitionTreeIds:[item.definitionTreeId],
                        definitionTemps:[item.definitionId],
                        originalData:[item],
                    "nodeType": 3,
                    definitionIds,
                    type: "top",
                    tid:item.definitionTreeId,
                    spanType:item.spanType,
                    definitionTreeLevel: item.definitionTreeLevel,
                    operateType: "update",
                    bridgeId: sectionData.bridgeId
                }
            });
        }
        
    }
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
      };
    render() {
        const {sectionData,commondShow}=this.props;
        const { data, treeData, selectActive, selectedRowKeys, loading } = this.state;
        const { getFieldDecorator } = this.props.form;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const columns = [
            {
                title: '构件名称',
                dataIndex: 'instanceName',
            },
            {
                title: '构件类型',
                dataIndex: 'definitionType',
            },
            {
                title: '起止桩号',
                dataIndex: 'code',
            },
            {
                title: '编辑构件',
                key: 'action',
                width:"260px",
                render: (text, record) => <span className="operate"><a onClick={(e) => this.replaceComponent(e, record)}><Icon type="retweet" /><span>构件替换</span></a> <a onClick={(e) => this.editComponentProp(e, record)}><Icon type="edit" /><span>属性编辑</span></a> <a onClick={(e) => this.deleteComponent(e, record)}><Icon type="delete" /><span>删除构件</span></a></span>,
            },
        ];
        return (
            <div className="pierComponentsBox">
                <Form style={{padding:"10px 15px"}}  labelCol={{ span: 9 }}
                    wrapperCol={{ span: 15 }}>

                    <div>
                        <Form.Item label='联号'>
                            {getFieldDecorator('designStage', {
                                rules: [
                                    { required: true, message: '联号' }
                                ],
                                initialValue:sectionData?sectionData.listName+'('+sectionData.express+')':undefined
                            })(
                                <Input disabled placeholder="联号"></Input>
                            )}
                        </Form.Item>
                        <Form.Item label='构件类型'>
                            {getFieldDecorator('designStage', {
                                rules: [
                                    { required: true, message: '构件类型' }
                                ]
                            })(
                                <StructureTreeSelect onSelect={this.onSelect} treeData={treeData} onLoaded={(context) => {
                                    this.setState({
                                        structureTreeSelectContext: context
                                    })
                                }}></StructureTreeSelect>
                            )}
                        </Form.Item>
                    </div>
                    <div className="btnBox"><Button onClick={this.addStructures}>添加构件</Button><Button disabled={!selectedRowKeys.length} onClick={this.massEditProp}>编辑属性</Button><Button disabled={!selectedRowKeys.length} onClick={this.massReplace}>构件替换</Button><Button disabled={!selectedRowKeys.length} onClick={this.massDelete}>删除构件</Button></div>
                </Form>
                <div className="tableBox">
                    <Table loading={loading} scroll={{ y: commondShow?280:360 }} pagination={false} rowSelection={selectActive ? rowSelection : false} rowKey={record => record.id} loading={loading} columns={columns} dataSource={data} />
                </div>
            </div>
        )
    }
}
export default connect(
    ({ }) => ({}),
    dispatch => ({

        getTopDefinitionInstanceList: (values) => dispatch({
            type: 'structure/getTopDefinitionInstanceList',
            payload: values
        }),
        getTopDefinitionTreeList: (values) => dispatch({
            type: 'structure/getTopDefinitionTreeList',
            payload: values
        }),
        deleteDefinitionInstance: (values,onSuccess,onError) => dispatch({
            type: 'structure/deleteDefinitionInstance',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
    })
)(Form.create('sectionStructures', {

})(sectionStructures))